package cn.wildfire.chat.app.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.ExtendSplashActivity;
import com.sourcemuch.im.caiba.InterfaceReceiversHub;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.SuperService;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.classes.ResponseEntity;
import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.SPUtils;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.kit.ChatManagerHolder;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;

/**
 * Create by HEKE, 2019/10/14 15:40
 * TODO 修改密码界面
 */
public class ModifyPasswordActivity extends WfcBaseActivity {

    @BindView(R2.id.et_orign_password)
    EditText etOrignPassword;
    @BindView(R2.id.et_new_password)
    EditText etNewPassword;
    @BindView(R2.id.et_confirm_password)
    EditText etConfirmPassword;
    @BindView(R2.id.iv_orgin_password_hide_or_show)
    ImageView ivOrginPasswordHideOrShow;
    @BindView(R2.id.iv_new_password_hide_or_show)
    ImageView ivNewPasswordHideOrShow;
    @BindView(R2.id.iv_confirm_password_hide_or_show)
    ImageView ivConfirmPasswordHideOrShow;
    @BindView(R2.id.oringinPasswordLayout)
    RelativeLayout oringinPasswordLayout;
    @BindView(R2.id.tv_new_password)
    TextView tv_new_password;
    @BindView(R2.id.oringinSplitorView)
    View oringinSplitorView;

    private UserInfo userInfo;
    private boolean havaPassword;

    @Override
    protected int contentLayout() {
        return R.layout.activity_modify_password;
    }

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 2);
        setSearchLayoutVisibility(false);
        Intent intent = getIntent();
        if (intent != null) {
            userInfo = intent.getParcelableExtra("userInfo");
            havaPassword = intent.getBooleanExtra("havaPassword", false);
            if (userInfo != null) {
                setReplaceTitle(null, R.string.set_xintui_password_title);
                if (havaPassword) {
                    oringinPasswordLayout.setVisibility(View.VISIBLE);
                } else {
                    oringinPasswordLayout.setVisibility(View.GONE);
                    tv_new_password.setText(R.string.set_password_title);
                    etNewPassword.setHint(R.string.password_hint);
                    oringinSplitorView.setVisibility(View.GONE);
                }
            } else {
                setReplaceTitle(null, R.string.modify_password);
            }
        }
    }

    private boolean orginPasswordShow;
    private boolean newPasswordShow;
    private boolean confirmPasswordShow;

    @OnClick({R2.id.btn_set_security_question_finish, R2.id.iv_orgin_password_hide_or_show, R2.id.iv_new_password_hide_or_show, R2.id.iv_confirm_password_hide_or_show})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_set_security_question_finish) {
            setNewPassword();
        } else if (id == R.id.iv_orgin_password_hide_or_show) {
            if (orginPasswordShow) {
                orginPasswordShow = false;
                ivOrginPasswordHideOrShow.setImageResource(R.mipmap.password_hide);
                etOrignPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                etOrignPassword.setSelection(etOrignPassword.getText().toString().length());
            } else {
                orginPasswordShow = true;
                ivOrginPasswordHideOrShow.setImageResource(R.mipmap.password_show);
                etOrignPassword.setInputType(InputType.TYPE_CLASS_TEXT);
                etOrignPassword.setSelection(etOrignPassword.getText().toString().length());
            }
        } else if (id == R.id.iv_new_password_hide_or_show) {
            if (newPasswordShow) {
                newPasswordShow = false;
                ivNewPasswordHideOrShow.setImageResource(R.mipmap.password_hide);
                etNewPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                etNewPassword.setSelection(etNewPassword.getText().toString().length());
            } else {
                newPasswordShow = true;
                ivNewPasswordHideOrShow.setImageResource(R.mipmap.password_show);
                etNewPassword.setInputType(InputType.TYPE_CLASS_TEXT);
                etNewPassword.setSelection(etNewPassword.getText().toString().length());
            }
        } else if (id == R.id.iv_confirm_password_hide_or_show) {
            if (confirmPasswordShow) {
                confirmPasswordShow = false;
                ivConfirmPasswordHideOrShow.setImageResource(R.mipmap.password_hide);
                etConfirmPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                etConfirmPassword.setSelection(etConfirmPassword.getText().toString().length());
            } else {
                confirmPasswordShow = true;
                ivConfirmPasswordHideOrShow.setImageResource(R.mipmap.password_show);
                etConfirmPassword.setInputType(InputType.TYPE_CLASS_TEXT);
                etConfirmPassword.setSelection(etConfirmPassword.getText().toString().length());
            }
        }
    }

    /**
     * 设置密码回调结果
     *
     * @param ret 0失败，1成功
     */
    private void setOrModifyPasswordResult(int ret) {
        setResult((ret == 1) ? Activity.RESULT_OK : Activity.RESULT_CANCELED);
        finish();
    }

    private void setNewPassword() {
        String newPassword = etNewPassword.getText().toString().trim();
        String newPasswordCheck = etConfirmPassword.getText().toString().trim();

        if (TextUtils.isTextEmpty(newPassword)) {
            ToastTip.tip(getString(R.string.password_can_not_full));
            return;
        }

        if (newPassword.length() < 6) {
            ToastTip.tip(getString(R.string.checked_password_is_less));
            return;
        }

        if (TextUtils.isTextEmpty(newPasswordCheck)) {
            ToastTip.tip(getString(R.string.password_can_not_full));
            return;
        }

        if (newPasswordCheck.length() < 6) {
            ToastTip.tip(getString(R.string.checked_password_is_less));
            return;
        }

        if (!newPassword.equals(newPasswordCheck)) {
            ToastTip.tip(getString(R.string.checked_password_not_same));
            return;
        }

        // 初次设置密码
        if (userInfo != null && !havaPassword) {
            if (newPassword.length() > 12 || newPasswordCheck.length() > 12) {
                ToastTip.tip(getString(R.string.checked_password_is_too_long));
                return;
            }
            HashMap<String, Object> params = new HashMap<>();
            params.put("confirmPassword", newPasswordCheck);
            params.put("password", newPassword);
            params.put("uid", userInfo.uid);
            OkHttpRequest.getInstance(this).requestAsynJsonObject(ServerUrlClient.RESET_PASSWORD, params, new ReqCallBack<String>() {

                @Override
                public void onReqSuccess(String result) {
                    try {
                        ResponseEntity responseEntity = new ResponseEntity(result);
                        if (responseEntity.isSuccess()) {
                            ToastTip.tip(getString(R.string.password_set_success));
                            setOrModifyPasswordResult(1);
                        } else {
                            setOrModifyPasswordResult(0);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onReqFailed(String errorMsg) {
                    Log.e("#### SetPassword", " errorMsg : " + errorMsg);
                    setOrModifyPasswordResult(0);
                }
            }).request();
            return;
        }

        String orignPassword = etOrignPassword.getText().toString().trim();
        if (TextUtils.isTextEmpty(orignPassword) || orignPassword.length() < 6) {
            ToastTip.tip(getString(R.string.orign_password_failure));
            return;
        }

        if (orignPassword.length() > 12 || newPassword.length() > 12 || newPasswordCheck.length() > 12) {
            ToastTip.tip(getString(R.string.checked_password_is_too_long));
            return;
        }

        HashMap<String, Object> params = new HashMap<>();
        params.put("confirmNewPwd", newPasswordCheck);
        params.put("newPwd", newPassword);
        params.put("originalPwd", orignPassword);
        params.put("uid", ChatManager.Instance().getUserId());

        OkHttpRequest.getInstance(this).requestAsynJsonObject(ServerUrlClient.PERSONALCENTER_RESET_PASSWORD, params, new ReqCallBack<Object>() {
            @Override
            public void onReqSuccess(Object result) {
                ResponseEntity<JsonObject, String> responseEntity = new ResponseEntity<>(result.toString());
                if (responseEntity.isSuccess()) {
                    ToastTip.tip(getString(R.string.reset_success));
                    SPUtils.setSingle(ModifyPasswordActivity.this, "REMENBER", "remenber", "0");
                    exit();
                } else if (responseEntity.getErrorCode().equals("37")) {
                    ToastTip.tip(responseEntity.message);
                    modifyFailure();
                } else {
                    ToastTip.tip(responseEntity.message);
                    modifyFailure();
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                ToastTip.tip(getString(R.string.request_failure));
                modifyFailure();
            }
        }).request();
    }

    /**
     * 修改密码失败
     */
    private void modifyFailure() {
        // 账号与安全进入更改密码
        if (userInfo != null && havaPassword) {
            setOrModifyPasswordResult(0);
        }
    }

    @SuppressLint({"ApplySharedPref", "StaticFieldLeak"})
    void exit() {
        try {
            new AsyncTask<String, Integer, String>() {
                @Override
                protected String doInBackground(String... strings) {
                    try {
                        // 解除小米推送绑定
                        if (userInfo != null && !TextUtils.isTextEmpty(userInfo.uid)) {
                            InterfaceReceiversHub.unsetMiPushAccount(CaiBaChatApp.getContext(), userInfo.uid);
                        }
                        // 修改退出登入后，登入另一个账号，应用信息依然是上一个账号信息。
                        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
                        sp.edit().clear().commit(); // apply与commit的区别，commit即时保存
                        // 更换至删除会话信息后再进行IM服务断开连接操作
                        ChatManagerHolder.gChatManager.disconnect(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    try {
                        // 清空管理员的会话内容，用于保证下次登入信息只显示一条
                        Conversation conversation = new Conversation(Conversation.ConversationType.Single, "admin");
                        ChatManager.Instance().clearMessages(conversation);
                        ChatManager.Instance().removeConversation(conversation, true);
                        // 关闭守护服务
                        stopService(new Intent(ModifyPasswordActivity.this, SuperService.class));
                        // 回程序登入界面
                        Intent intent = new Intent(ModifyPasswordActivity.this, ExtendSplashActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("fromLogout", true);
                        startActivity(intent);
                        finish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
